package com.ruoyi.mdkt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.mdkt.entity.Goods;
import com.ruoyi.mdkt.entity.Pack;
import com.ruoyi.mdkt.entity.Pet;
import com.ruoyi.mdkt.entity.PetLog;
import com.ruoyi.mdkt.mapper.PetMapper;
import com.ruoyi.mdkt.service.GoodsService;
import com.ruoyi.mdkt.service.PackService;
import com.ruoyi.mdkt.service.PetLogService;
import com.ruoyi.mdkt.service.PetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ruoyi.mdkt.utils.GradeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gwl
 * @since 2022-10-22
 */
@Service
public class PetServiceImpl extends ServiceImpl<PetMapper, Pet> implements PetService {
    @Autowired
    private PetService petService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private PetLogService petLogService;
    @Autowired
    private PackService packService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updatePet(Long goodsId, Long userId) {
        LambdaQueryWrapper<Pet> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Pet::getUserId,userId);
        Pet one = petService.getOne(wrapper);

        LambdaQueryWrapper<Pack> packLambdaQueryWrapper = new LambdaQueryWrapper<>();
        packLambdaQueryWrapper.eq(Pack::getUserId,userId)
                .eq(Pack::getGoodsId,goodsId);
        Pack pack = packService.getOne(packLambdaQueryWrapper);
        if (pack == null || pack.getNumber() == 0){
            return false;
        }
        pack.setNumber(pack.getNumber()-1);
        packService.updateById(pack);

        Goods goods = goodsService.getById(goodsId);
        PetLog petLog = new PetLog();
        petLog.setPetId(one.getId());
        petLog.setGoodsId(goodsId);
        petLog.setNumber(1);
        petLog.setOlderExperience(one.getExperience());
        petLog.setOlderGrade(one.getGrade());
        petLog.setNewExperience(one.getExperience()+goods.getEffect());
        if (one.getExperience()+goods.getEffect() >= GradeUtils.get(one.getGrade())){
            one.setGrade(one.getGrade()+1);
        }
        petLog.setNewGrade(one.getGrade());
        petLogService.save(petLog);

        one.setExperience(one.getExperience()+goods.getEffect());
        petService.updateById(one);
        return true;
    }

    @Override
    public Boolean newPet(Long userId) {
        Pet pet = new Pet();
        pet.setUserId(userId);
        pet.setLastLogonTime(LocalDateTime.now());
        pet.setGrade(1);
        pet.setExperience(0);
        return petService.save(pet);
    }
}
